package com.hudongwx.yuan_sdjj.fragment;


import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hudongwx.yuan_sdjj.R;
import com.hudongwx.yuan_sdjj.utils.API.API;
import com.hudongwx.yuan_sdjj.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.fragment_gather_praiseer)
public class GatherPraiseerFragment extends Fragment {
    //下拉菜单的根标签
    @ViewInject(R.id.gather_type_tv)
    private TextView tvType;
    @ViewInject(R.id.gather_brand_tv)
    private TextView tvBrand;
    @ViewInject(R.id.gather_sort_tv)
    private TextView tvSort;
    @ViewInject(R.id.gather_type_iv)
    private ImageView ivType;
    @ViewInject(R.id.gather_brand_iv)
    private ImageView ivBrand;
    @ViewInject(R.id.gather_sort_iv)
    private ImageView ivSort;
    //布局控件
    @ViewInject(R.id.gather_recycler_view)
    private RecyclerView recyclerView;
    @ViewInject(R.id.gather_header_iv)
    private ImageView ivHeader;
    @ViewInject(R.id.gather_remove_rl)
    private RelativeLayout rLayout;
    @ViewInject(R.id.gather_show_fl)
    private FrameLayout fLayout;
    //加载刷新显示
    private MyAdapter myAdapter;
    private GridLayoutManager gridLayoutManager;
    //获取网络链接的关键参数
    private int nowPage = 1;
    private String type = null;
    private String brand = "0";
    private String sort = "0";

    //type的弹窗
    private PopupWindow popWindowType;
    private LinearLayout popViewType;
    //brand的弹窗
    private PopupWindow popWindowBrand;
    private LinearLayout popViewBrand;
    //sort的弹窗
    private PopupWindow popWindowSort;
    private LinearLayout popViewSort;

    //这个是分类，对应链接中的cat_id字段，在不同分类下的的取值
    private String[] types = new String[]{null, "2", "3", "5", "4", "8"};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        init();
        return view;
    }

    /**
     * 分类样式这一栏
     *
     * @param view
     */
    @Event(R.id.gather_type_ll)
    private void clickType(final View view) {//点击事件 不能改变状态
        //默认为未选中
        if (view.isSelected()) {
            //设置为为选中，也就是关闭的时候
            view.setSelected(false);
            if (null != popWindowType) {
                popWindowType.dismiss();
            }
        } else {
            //设定当前为选中状态
            view.setSelected(true);
            if (null == popWindowType) { //如果未曾创建过popWindow
                //解析布局
                popViewType = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.gather_type_popwindow, null);
                //创建一个PopupWindow 并且设定布局
                popWindowType = new PopupWindow(popViewType, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                //添加一个点击事件
                View.OnClickListener onClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView tv = (TextView) v;
                        //这就可以实现点开点关功能
                        popWindowType.dismiss();
                        view.setSelected(false);
                        //根据标签返回的页码折射出我所需要的type类型
                        type = types[Integer.parseInt(v.getTag() + "")];
                        //重置页码

                        if ("0".equals(v.getTag() + "")) {
                            //如果选第一个条目
                            nowPage = 1;
                            tvType.setText("分类");
                        } else {
                            //把选中标签的名字提上来 用上面找到控件
                            tvType.setText(tv.getText());
                        }

                        //初始化item
                        setDropDownItem(popViewType, tv);
                        //清除以前的数据
                        myAdapter.clear();
                        loadData();
                    }
                };
                //给内部的按钮添加点击事件
                int len = popViewType.getChildCount();
                for (int i = 0; i < len; i++) {
                    View childAt = popViewType.getChildAt(i);
                    //因为这一页的标签是不规律的
                    childAt.setTag(i + "");
                    //把上面的点击事件设置给按钮
                    childAt.setOnClickListener(onClickListener);
                    //设置默认选中项
                    if (0 == i) {
                        childAt.setSelected(true);
                    }
                }
                //点击黑色的区域
                popViewType.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popWindowType.dismiss();
                        //下次进来重新刷新
                        view.setSelected(false);
                    }
                });
            }
            //显示布局   并且拦截其他两个页面
            popWindowType.showAsDropDown(view);
            if (null != popWindowBrand) {
                popWindowBrand.dismiss();
                ivBrand.setSelected(false);
            }
            if (null != popWindowSort) {
                popWindowSort.dismiss();
                ivSort.setSelected(false);
            }
        }
    }

    /**
     * 筛选样式这一栏
     *
     * @param view
     */
    @Event(R.id.gather_brand_ll)
    private void clickBrand(final View view) {//点击事件 不能改变状态
        //默认为未选中
        if (view.isSelected()) {
            //设置为为选中，也就是关闭的时候
            view.setSelected(false);
            if (null != popWindowBrand) {
                popWindowBrand.dismiss();
            }
        } else {
            //设定当前为选中状态
            view.setSelected(true);
            if (null == popWindowBrand) { //如果未曾创建过popWindow
                //解析布局
                popViewBrand = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.gather_brand_popwindow, null);
                //创建一个PopupWindow 并且设定布局
                popWindowBrand = new PopupWindow(popViewBrand, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                //添加一个点击事件
                View.OnClickListener onClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView tv = (TextView) v;
                        //这就可以实现点开点关功能
                        popWindowBrand.dismiss();
                        view.setSelected(false);
                        //根据标签返回的页码折射出我所需要的type类型
                        brand = v.getTag() + "";
                        //重置页码
                        nowPage = 1;
                        if ("0".equals(v.getTag() + "")) {
                            //如果选第一个条目
                            tvBrand.setText("筛选");
                        } else {
                            //把选中标签的名字提上来,用上面找到控件
                            tvBrand.setText(tv.getText());
                        }
                        //初始化item
                        setDropDownItem(popViewBrand, tv);
                        //清除以前的数据
                        myAdapter.clear();
                        loadData();
                    }
                };
                //给内部的按钮添加点击事件
                int len = popViewBrand.getChildCount();
                for (int i = 0; i < len; i++) {
                    View childAt = popViewBrand.getChildAt(i);
                    //因为这一页的标签是不规律的
                    childAt.setTag(i + "");
                    //把上面的点击事件设置给按钮
                    childAt.setOnClickListener(onClickListener);
                    //设置默认选中项
                    if (0 == i) {
                        childAt.setSelected(true);
                    }
                }
                //点击黑色的区域
                popViewBrand.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popWindowBrand.dismiss();
                        //下次进来重新刷新
                        view.setSelected(false);
                    }
                });
            }
            //显示布局 并且拦截其他两个页面
            popWindowBrand.showAsDropDown(view);
            if (null != popWindowType) {
                popWindowType.dismiss();
                ivType.setSelected(false);

            }
            if (null != popWindowSort) {
                popWindowSort.dismiss();
                ivSort.setSelected(false);
            }
        }
    }

    /**
     * 排序样式这一栏
     *
     * @param view
     */
    @Event(R.id.gather_sort_ll)
    private void clickSort(final View view) {//点击事件 不能改变状态
        //默认为未选中
        if (view.isSelected()) {
            //设置为为选中，也就是关闭的时候
            view.setSelected(false);
            if (null != popWindowSort) {
                popWindowSort.dismiss();
            }
        } else {
            //设定当前为选中状态
            view.setSelected(true);
            if (null == popWindowSort) { //如果未曾创建过popWindow
                //解析布局
                popViewSort = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.gather_sort_popwindow, null);
                //创建一个PopupWindow 并且设定布局
                popWindowSort = new PopupWindow(popViewSort, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                //添加一个点击事件
                View.OnClickListener onClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView tv = (TextView) v;
                        //这就可以实现点开点关功能
                        popWindowSort.dismiss();
                        view.setSelected(false);
                        //根据标签返回的页码折射出我所需要的type类型
                        type = v.getTag() + "";
                        //重置页码
                        nowPage = 1;
                        if ("0".equals(v.getTag() + "")) {
                            //如果选第一个条目
                            tvSort.setText("排序");
                        } else {
                            //把选中标签的名字提上来 用上面找到控件
                            tvSort.setText(tv.getText());
                        }

                        //初始化item
                        setDropDownItem(popViewSort, tv);
                        //清除以前的数据
                        myAdapter.clear();
                        loadData();
                    }
                };
                //给内部的按钮添加点击事件
                int len = popViewSort.getChildCount();
                for (int i = 0; i < len; i++) {
                    View childAt = popViewSort.getChildAt(i);
                    //因为这一页的标签是不规律的
                    childAt.setTag(i + "");
                    //把上面的点击事件设置给按钮
                    childAt.setOnClickListener(onClickListener);
                    //设置默认选中项
                    if (0 == i) {
                        childAt.setSelected(true);
                    }
                }
                //点击黑色的区域
                popViewSort.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popWindowSort.dismiss();
                        //下次进来重新刷新
                        view.setSelected(false);
                    }
                });
            }
            //显示布局  并且拦截其他两个页面
            popWindowSort.showAsDropDown(view);
            if (null != popWindowBrand) {
                popWindowBrand.dismiss();
                ivBrand.setSelected(false);

            }
            if (null != popWindowType) {
                popWindowType.dismiss();
                ivType.setSelected(false);
            }
        }
    }

    private void setDropDownItem(LinearLayout linearLayout, TextView tv) {
        int len = linearLayout.getChildCount();
        for (int i = 0; i < len; i++) {
            TextView childView = (TextView) linearLayout.getChildAt(i);
            childView.setSelected(false);
            //设置边距，左上右下
            childView.setPadding(
                    getResources().getDimensionPixelSize(R.dimen.common_10),
                    getResources().getDimensionPixelSize(R.dimen.common_2), 0,
                    getResources().getDimensionPixelSize(R.dimen.common_2)
            );
            childView.setCompoundDrawables(null, null, null, null);
        }
        //设置此条目返回text的边距
        tv.setPadding(
                getResources().getDimensionPixelSize(R.dimen.common_5),
                getResources().getDimensionPixelSize(R.dimen.common_2), 0,
                getResources().getDimensionPixelSize(R.dimen.common_2));
        //设置图片
        Drawable drawable = getResources().getDrawable(R.drawable.collection_pick);
        //这一步必须设置，不然没有内容
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tv.setCompoundDrawables(drawable, null, null, null);
        tv.setSelected(true);
    }


    /**
     * 初始化界面
     */
    private void init() {
        gridLayoutManager = new GridLayoutManager(getActivity(), 4);
        recyclerView.setLayoutManager(gridLayoutManager);
        myAdapter = new MyAdapter();
        recyclerView.setAdapter(myAdapter);
        loadData();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                //recyclerView的状态处于停止并且gridLayoutManager到了最后一个位置，就可以继续加载数据了
                if (newState == recyclerView.SCROLL_STATE_IDLE &&
                        gridLayoutManager.findLastCompletelyVisibleItemPosition() + 1 == myAdapter.getItemCount()) {
                    loadData();
                }

            }
        });

    }

    /**
     * 从网页上加载数据
     */
    private void loadData() {
        //发送加载数据的请求
        RequestParams requestParams = new RequestParams(API.getUrlPraise(type, brand, sort, nowPage + ""));
        x.http().get(requestParams, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                List<PraiseItem> items = json2Data(result);
                if (0 == items.size() && nowPage == 1) {
                    //如果没有数据
                    rLayout.setVisibility(View.VISIBLE);
                    fLayout.setVisibility(View.GONE);
                    return;
                } else if (0 == items.size() && nowPage != 1) {
                    //到最后一页
                    Toast.makeText(getActivity(), "已经到底了", Toast.LENGTH_SHORT).show();
                }
                //正常显现的情况
                rLayout.setVisibility(View.GONE);
                fLayout.setVisibility(View.VISIBLE);

                myAdapter.addData(items);
                //判断是否是第一页，是的话就可以加载头部
                if (1 == nowPage) {
                    try {
                        x.image().bind(ivHeader, result.getString("title"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                //页码自加
                nowPage++;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * recycler的适配器
     */
    class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
        //初始化装数据的容器
        private List<PraiseItem> data = new ArrayList<>();

        public MyAdapter(List<PraiseItem> data) {
            //有多得数据的时候直接加入进来
            this.data.addAll(data);
            notifyDataSetChanged();
        }

        public MyAdapter() {
        }

        public void clear() {
            data.clear();
            notifyDataSetChanged();
        }

        /**
         * 加载第一页
         *
         * @param datas
         */
        public void addData(List<PraiseItem> datas) {
            data.addAll(datas);
            //通知更改的范围 以前加载出来的所有
            notifyItemChanged(data.size() - datas.size(), datas.size());
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.gather_item, null);
            //送去ViewHolder找出控件
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            //绑定每个item的图片
            PraiseItem item = data.get(position);
            x.image().bind(holder.iv, item.brandIcon);
            //判断item的状态，是集满，降价，未满
            if ("1".equals(item.isDown)) {//正在降价
                //绘制文本左边显示的图片
                Drawable drawable = getResources().getDrawable(R.drawable.down);
                //是指图片大小
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                //设置图片的位置
                holder.tv.setCompoundDrawables(drawable, null, null, null);
                holder.tv.setBackgroundResource(0);
                holder.tv.setText("闪降中");
                holder.tv.setTextColor(Color.RED);
            } else if (item.likeNum >= item.max) {//集满了
                Drawable drawable = getResources().getDrawable(R.drawable.collection_full);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                holder.tv.setCompoundDrawables(drawable, null, null, null);
                holder.tv.setBackgroundResource(0);
                holder.tv.setText("满赞");
                holder.tv.setTextColor(Color.RED);
            } else {//未集满
                Drawable drawable = getResources().getDrawable(R.drawable.collection_press);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                holder.tv.setCompoundDrawables(drawable, null, null, null);
                holder.tv.setBackgroundResource(R.drawable.click_praise_item_gather);
                holder.tv.setText("点赞");
                holder.tv.setTextColor(Color.BLACK);
            }
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    /**
     * 创建一个ViewHolder的类，用于初始化解析的item布局，并且可以在复用的时候调用
     */
    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView iv;
        TextView tv;

        public MyViewHolder(View itemView) {
            super(itemView);
            iv = (ImageView) itemView.findViewById(R.id.gather_item_iv);
            tv = (TextView) itemView.findViewById(R.id.gather_item_tv);
        }
    }

    /**
     * 用于解析解析json数据的方法
     *
     * @param jsonObject 从数据原丢过来解析的数据
     * @return 解析后的数据
     */
    public List<PraiseItem> json2Data(JSONObject jsonObject) {
        List<PraiseItem> list = new ArrayList<>();
        try {
            JSONArray jsonArray = jsonObject.getJSONArray("brands");
            int len = jsonArray.length();
            for (int i = 0; i < len; i++) {
                list.add(new PraiseItem(jsonArray.getJSONObject(i)));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 创建一个聚赞的实体类
     */
    class PraiseItem {
        private int brandId;
        private int isLike;
        private String brandName;
        private String brandIcon;
        private int likeNum;
        private int max;
        private String isDown;

        // 在构造器里面解析每一条json数据，初始化数据
        public PraiseItem(JSONObject item) throws JSONException {
            brandId = item.getInt("brandId");
            isLike = item.getInt("isLike");
            brandName = item.getString("brandName");
            brandIcon = item.getString("brandIcon");
            likeNum = item.getInt("likeNum");
            max = item.getInt("max");
            isDown = item.getString("isDown");
        }

        public int getBrandId() {
            return brandId;
        }

        public void setBrandId(int brandId) {
            this.brandId = brandId;
        }

        public int getIsLike() {
            return isLike;
        }

        public void setIsLike(int isLike) {
            this.isLike = isLike;
        }

        public String getBrandName() {
            return brandName;
        }

        public void setBrandName(String brandName) {
            this.brandName = brandName;
        }

        public String getBrandIcon() {
            return brandIcon;
        }

        public void setBrandIcon(String brandIcon) {
            this.brandIcon = brandIcon;
        }

        public int getLikeNum() {
            return likeNum;
        }

        public void setLikeNum(int likeNum) {
            this.likeNum = likeNum;
        }

        public int getMax() {
            return max;
        }

        public void setMax(int max) {
            this.max = max;
        }

        public String getIsDown() {
            return isDown;
        }

        public void setIsDown(String isDown) {
            this.isDown = isDown;
        }
    }
}
